<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "UserCoupon".
 */
class UserCoupon extends ActiveRecord {

    // 注册送优惠劵
    const RegisterDeliver = 1;
    const RegisterInviter = 2;
    
    // @name 状态
    const StatusInit = 0;
    const StatusUsable = 1;
    const StatusUsed = 10;
    public static $statusSelector = [
        // self::StatusInit => ['title' => '待激活', 'status' => 'gray'],
        self::StatusUsable => ['title' => '可使用', 'status' => 'blue'],
        self::StatusUsed => ['title' => '已使用', 'status' => 'green'],
    ];

    // only define rules for those attributes that
    // will receive user inputs.
    public function rules()
    {
        return [
            [['user_id', 'coupon_id', 'status'], 'required'],
            [['user_id', 'coupon_id', 'active_at', 'begin_at', 'finish_at', 'status', 'deleted_at'], 'integer'],
        ];
    }
    /**
     * @name 字段名称
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'user_id' => '用户编号',
            'coupon_id' => '优惠劵编号',
            'active_at' => '激活时间',
            'begin_at' => '有效开始时间',
            'finish_at' => '最后使用时间',
            'status' => '状态',
            'deleted_at' => '删除时间',
        ];
    }

    /**
     * @name 获取user信息
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }
    
    /**
     * @name 获取优惠劵
     * @return \yii\db\ActiveQuery
     */
    public function getCoupon()
    {
        return $this->hasOne(Coupon::className(), ['id' => 'coupon_id']);
    }

    /**
     * @name 判断是否可用
     * @param $order array 订单参数
     * @return boolean
     */
    public function usable($order)
    {
        if( ! in_array($this->status, [static::StatusUsable])) {
            return false;
        }
        if($this->begin_at >= time()) {
            return false;
        }
        if($this->finish_at < time()) {
            return false;
        }
        return $this->coupon->usable($order);
    }
    
    /**
     * 计算优惠金额
     * @param $order array 订单参数
     * @return integer
     */
    public function deduct($order)
    {
        return $this->coupon->deduct($order);
    }
    
    /**
     * 使用优惠劵
     * @return boolean
     */
    public function used()
    {
        $this->status = static::StatusUsed;
        $this->updated_at = time();
        return $this->save();
    }
    
    /**
     * 发放优惠劵
     * @param $couponId int 优惠劵编号
     * @param $userId int 用户编号
     * @return boolean
     */
    public static function creator($couponId, $userId)
    {
        if(empty($couponId) || empty($userId)) {
            return false;
        }
        $userCoupon = new static();
        $userCoupon->coupon_id = $couponId;
        $userCoupon->user_id = $userId;
        if(empty($userCoupon->coupon)) {
            return false;
        }
        if( ! $userCoupon->coupon->receive()) {
            return false;
        }
        $userCoupon->active_at = time();
        $userCoupon->begin_at = time();
        switch($userCoupon->coupon->timeout) {
            case Coupon::TimeoutFixed: {
                if($userCoupon->coupon->timeout_value < date('Y-m-d')) {
                    return false;
                }
                $userCoupon->finish_at = strtotime($userCoupon->coupon->timeout_value);
            } break;
            case Coupon::TimeoutByDay: {
                $userCoupon->finish_at = strtotime("+{$userCoupon->coupon->timeout_value} days");
            } break;
            default: {
                return false;
            }
        }
        $userCoupon->status = static::StatusUsable;
        return $userCoupon->save();
    }
    
    /**
     * 获取可用优惠劵
     * @param $userId integer 用户编号
     * @param $type integer 优惠劵类型
     * @return array
     */
    public static function findor($userId, $type = Coupon::TypeEmployment)
    {
        return static::find()->select(static::tableName().'.id, '.Coupon::tableName().'.title')
            ->leftJoin(Coupon::tableName(), Coupon::tableName().'.id = coupon_id')
            ->where(['user_id' => $userId, Coupon::tableName().'.type' => $type, static::tableName().'.status' => UserCoupon::StatusUsable])
            ->andWhere(['<=', 'begin_at', time()])
            ->andWhere(['>', 'finish_at', time()])
            ->andWhere(['=', static::tableName().'.deleted_at', '0'])
            // ->createCommand()->getRawSql()
            ->asArray()->all();
    }
}